package cn.consult.sys.service.impl;

import cn.consult.netty.ElectricityMeterUtil;
import cn.consult.netty.InstructConstant;
import cn.consult.netty.InstructTypeConstant;
import cn.consult.netty.SendInstructsService;
import cn.consult.sys.dao.*;
import cn.consult.sys.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.consult.sys.service.TWeEquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 水电设备管理(TWeEquipment)表服务实现类
 *
 * @author makejava
 * @since 2024-04-09 09:13:14
 */
@Service("tWeEquipmentService")
public class TWeEquipmentServiceImpl extends ServiceImpl<TWeEquipmentDao, TWeEquipment> implements TWeEquipmentService {

    @Autowired
    TPlaceBuildingDao tPlaceBuildingDao;
    @Autowired
    TPlaceFloorDao tPlaceFloorDao;
    @Autowired
    TPlaceRoomDao tPlaceRoomDao;
    @Autowired
    TWeGatewayConfigDao tWeGatewayConfigDao;

    @Autowired
    SendInstructsService sendInstructsService;


    @Override
    public IPage<TWeEquipment> selectPage(Map<String, Object> params) {

        LambdaQueryWrapper<TWeEquipment> queryWrapper = new LambdaQueryWrapper<>();

        if (params.get("equipmentNumber") != null && params.get("equipmentNumber") != "") {
            queryWrapper.eq(TWeEquipment::getEquipmentNumber, params.get("equipmentNumber").toString());
        }
        if (params.get("equipmentName") != null && params.get("equipmentName") != "") {
            queryWrapper.eq(TWeEquipment::getEquipmentName, params.get("equipmentName").toString());
        }
        //传过来的是楼栋id的话就代表只选择了楼栋
        if (params.get("bulidingId") != null && params.get("bulidingId") != "") {
            queryWrapper.eq(TWeEquipment::getBulidingId, params.get("bulidingId").toString());
        }
        //传过来的是楼层id的话就代表只选择了楼层 但是还要查询他的楼栋id
        if (params.get("floorId").toString() != null && params.get("floorId").toString() != "") {
            queryWrapper.eq(TWeEquipment::getFloorId, params.get("floorId").toString());

            TPlaceFloor tPlaceFloor = tPlaceFloorDao.selectById(params.get("floorId").toString());
            queryWrapper.eq(TWeEquipment::getBulidingId, tPlaceFloor.getFloorBuildingid());

        }
        //传过来的是房间id的话就代表只选择了房间 但是还要查询他的楼层id 楼栋id
        if (params.get("roomId").toString() != null && params.get("roomId").toString() != "") {
            queryWrapper.eq(TWeEquipment::getRoomId, params.get("roomId").toString());
            TPlaceRoom tPlaceRoom = tPlaceRoomDao.selectById(params.get("roomId").toString());
            TPlaceFloor tPlaceFloor = tPlaceFloorDao.selectById(tPlaceRoom.getRoomFloorid());
            queryWrapper.eq(TWeEquipment::getBulidingId, tPlaceFloor.getFloorBuildingid());
            queryWrapper.eq(TWeEquipment::getFloorId, tPlaceRoom.getRoomFloorid());
        }

        Page p = new Page();
        p.setCurrent(Integer.parseInt(params.get("pageNum").toString()));
        p.setSize(Integer.parseInt(params.get("pageSize").toString()));


        Page page = this.baseMapper.selectPage(p, queryWrapper);


        return page;
    }

    @Override
    public boolean saveWeEquipment(TWeEquipment tWeEquipment) {
        tWeEquipment.setCreateTime(LocalDate.now().toString());
        tWeEquipment.setJoinTime(LocalDate.now().toString());
        tWeEquipment.setEquipmentResidueMoney(0.0);
        tWeEquipment.setEquipmentResidueNumber(0);
        tWeEquipment.setJoinTime(LocalDate.now().toString());
        tWeEquipment.setEquipmentStatus(1);

        if (tWeEquipment.getRoomId() != null && tWeEquipment.getRoomId() != 0) {
            //选择房间  查询楼层  查询楼栋
            TPlaceRoom tPlaceRoom = tPlaceRoomDao.selectById(tWeEquipment.getRoomId());
            //查询楼层
            TPlaceFloor tPlaceFloor = tPlaceFloorDao.selectById(tPlaceRoom.getRoomFloorid());
            //查询楼层
            TPlaceBuilding tPlaceBuilding = tPlaceBuildingDao.selectById(tPlaceFloor.getFloorBuildingid());

            tWeEquipment.setBulidingId(Integer.valueOf(String.valueOf(tPlaceBuilding.getId())));
            tWeEquipment.setFloorId(Integer.valueOf(String.valueOf(tPlaceFloor.getId())));
            tWeEquipment.setRoomId(Integer.valueOf(String.valueOf(tPlaceRoom.getId())));

            tWeEquipment.setEquipmentAddress(tPlaceBuilding.getBuildingName() + "/" + tPlaceFloor.getFloorName() + "/" + tPlaceRoom.getRoomName());
        } else if (tWeEquipment.getFloorId() != null && tWeEquipment.getFloorId() != 0) {
            TPlaceFloor tPlaceFloor = tPlaceFloorDao.selectById(tWeEquipment.getFloorId());

            TPlaceBuilding tPlaceBuilding = tPlaceBuildingDao.selectById(tPlaceFloor.getFloorBuildingid());

            tWeEquipment.setBulidingId(Integer.valueOf(String.valueOf(tPlaceBuilding.getId())));
            tWeEquipment.setFloorId(Integer.valueOf(String.valueOf(tPlaceFloor.getId())));

            tWeEquipment.setEquipmentAddress(tPlaceBuilding.getBuildingName() + "/" + tPlaceFloor.getFloorName());

        } else if (tWeEquipment.getBulidingId() != null && tWeEquipment.getBulidingId() != 0) {
            TPlaceBuilding tPlaceBuilding = tPlaceBuildingDao.selectById(tWeEquipment.getBulidingId());


            tWeEquipment.setBulidingId(Integer.valueOf(String.valueOf(tPlaceBuilding.getId())));

            tWeEquipment.setEquipmentAddress(tPlaceBuilding.getBuildingName());
        }


        int insert = this.baseMapper.insert(tWeEquipment);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updateWeEquipment(TWeEquipment tWeEquipment) {
        tWeEquipment.setUpdateTime(LocalDate.now().toString());


        if (tWeEquipment.getRoomId() != null && tWeEquipment.getRoomId() != 0) {
            //选择房间  查询楼层  查询楼栋
            TPlaceRoom tPlaceRoom = tPlaceRoomDao.selectById(tWeEquipment.getRoomId());
            //查询楼层
            TPlaceFloor tPlaceFloor = tPlaceFloorDao.selectById(tPlaceRoom.getRoomFloorid());
            //查询楼层
            TPlaceBuilding tPlaceBuilding = tPlaceBuildingDao.selectById(tPlaceFloor.getFloorBuildingid());

            tWeEquipment.setBulidingId(Integer.valueOf(String.valueOf(tPlaceBuilding.getId())));
            tWeEquipment.setFloorId(Integer.valueOf(String.valueOf(tPlaceFloor.getId())));
            tWeEquipment.setRoomId(Integer.valueOf(String.valueOf(tPlaceRoom.getId())));

            tWeEquipment.setEquipmentAddress(tPlaceBuilding.getBuildingName() + "/" + tPlaceFloor.getFloorName() + "/" + tPlaceRoom.getRoomName());
        } else if (tWeEquipment.getFloorId() != null && tWeEquipment.getFloorId() != 0) {
            TPlaceFloor tPlaceFloor = tPlaceFloorDao.selectById(tWeEquipment.getFloorId());

            TPlaceBuilding tPlaceBuilding = tPlaceBuildingDao.selectById(tPlaceFloor.getFloorBuildingid());

            tWeEquipment.setBulidingId(Integer.valueOf(String.valueOf(tPlaceBuilding.getId())));
            tWeEquipment.setFloorId(Integer.valueOf(String.valueOf(tPlaceFloor.getId())));
            tWeEquipment.setRoomId(0);

            tWeEquipment.setEquipmentAddress(tPlaceBuilding.getBuildingName() + "/" + tPlaceFloor.getFloorName());

        } else if (tWeEquipment.getBulidingId() != null && tWeEquipment.getBulidingId() != 0) {
            TPlaceBuilding tPlaceBuilding = tPlaceBuildingDao.selectById(tWeEquipment.getBulidingId());


            tWeEquipment.setBulidingId(Integer.valueOf(String.valueOf(tPlaceBuilding.getId())));
            tWeEquipment.setFloorId(0);
            tWeEquipment.setRoomId(0);

            tWeEquipment.setEquipmentAddress(tPlaceBuilding.getBuildingName());
        }


        int update = this.baseMapper.updateById(tWeEquipment);
        if (update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean openWater(Long id) {
        ElectricityMeterUtil u = new ElectricityMeterUtil();
        //拿到当前水表的信息
        TWeEquipment tWeEquipment = this.baseMapper.selectById(id);
        //拿到水表的网关
        TWeGatewayConfig tWeGatewayConfig = tWeGatewayConfigDao.selectById(tWeEquipment.getEquipmentGateway());

        String s = ElectricityMeterUtil.deviceAddressConvert(tWeEquipment.getEquipmentNumber());

        String completeInstruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.WATER_METER_NO);

        return false;
    }

    public static void main(String[] args) {
        String wNumber = "00000220252344";
        String eNumber = "000000 967933";
        String s = ElectricityMeterUtil.deviceAddressConvert(wNumber);
        String e = ElectricityMeterUtil.deviceAddressConvert(eNumber);
        String completeInstruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.WATER_METER_NO);
        String instruct = ElectricityMeterUtil.getCompleteInstruct(e, InstructConstant.ELECTRICITY_METER_ON_INSTRUCT);
        System.out.println("电合闸" + instruct);
        System.out.println("开 阀 " + completeInstruct);
    }

    @Override
    public boolean closeWater(Long id) {
        return false;
    }


    @Override
    public boolean operationElectricity(Long id, Long type, HttpServletRequest request) {
        //先拿当前设备的信息
        TWeEquipment tWeEquipment = this.baseMapper.selectById(id);
        TWeGatewayConfig tWeGatewayConfig = tWeGatewayConfigDao.selectById(tWeEquipment.getEquipmentGateway());
        //目标网关
        String gatewayIp = tWeGatewayConfig.getGatewayIp();
        //操作的目标设备号码
        String equipmentNumber = tWeEquipment.getEquipmentNumber();
        //设备编号转换
        String s = ElectricityMeterUtil.deviceAddressConvert(equipmentNumber);
        //最终指令 根据以下判断
        String instruct = null;
        //操作类型
        String operationType = null;
        if (String.valueOf(type).equals(InstructTypeConstant.E_MAIN_GATE_NO.getKey())) {
            //电合闸
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_ON_INSTRUCT);
            operationType = InstructTypeConstant.E_MAIN_GATE_NO.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_MAIN_GATE_OFF.getKey())) {
            //电拉闸
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_PULL_INSTRUCT);
            operationType = InstructTypeConstant.E_MAIN_GATE_OFF.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_A_GATE_NO.getKey())) {
            //A合总闸
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_A_NO_INSTRUCT);
            operationType = InstructTypeConstant.E_A_GATE_NO.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_A_GATE_OFF.getKey())) {
            //A拉总闸
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_A_PULL_INSTRUCT);
            operationType = InstructTypeConstant.E_A_GATE_OFF.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_B_GATE_NO.getKey())) {
            //B合总闸
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_B_NO_INSTRUCT);
            operationType = InstructTypeConstant.E_B_GATE_NO.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_B_GATE_OFF.getKey())) {
            //B拉总闸
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_B_PULL_INSTRUCT);
            operationType = InstructTypeConstant.E_B_GATE_OFF.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_MAIN_PARSM_INFO.getKey())) {
            //获取电表参数
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_SUMMARY_INFO_INSTRUCT);
            operationType = InstructTypeConstant.E_MAIN_PARSM_INFO.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_BALANCE_SETUPA.getKey())) {
            //抄表记录
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_METER_USED_INSTRUCT);
            operationType = InstructTypeConstant.E_BALANCE_SETUPA.getKey();
        } else if (String.valueOf(type).equals(InstructTypeConstant.E_OPEN_ACCOUNT.getKey())) {
            //重新开户
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_OPEN_ACCOUNT);
            operationType = InstructTypeConstant.E_OPEN_ACCOUNT.getKey();
        }
        String ip = "/" + tWeGatewayConfig.getGatewayIp() + ":" + tWeGatewayConfig.getGatewayPort();
        Object[] openElectricities = sendInstructsService.sendInstructs(instruct, ip, request, equipmentNumber, operationType);
        return openElectricities != null ? true : false;
    }


    @Override
    public boolean operationWater(Long id, Long type, HttpServletRequest request) {
        //先拿当前设备的信息
        TWeEquipment tWeEquipment = this.baseMapper.selectById(id);
        TWeGatewayConfig tWeGatewayConfig = tWeGatewayConfigDao.selectById(tWeEquipment.getEquipmentGateway());
        //目标网关
        String gatewayIp = tWeGatewayConfig.getGatewayIp();
        //操作的目标设备号码
        String equipmentNumber = tWeEquipment.getEquipmentNumber();
        //设备编号转换
        String s = ElectricityMeterUtil.deviceAddressConvert(equipmentNumber);
        //最终指令 根据以下判断
        String instruct = null;
        //操作类型
        String operationType = null;
        if (type == 100) {
            //开阀
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.WATER_METER_NO);
            operationType = InstructTypeConstant.W_GATE_NO.getKey();
        } else if (type == 101) {
            //关阀
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.WATER_METER_OFF);
            operationType = InstructTypeConstant.W_GATE_OFF.getKey();
        } else if (type == 102) {
            //查询水表信息
            instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.WATER_METER_READ_DATA);
            operationType = InstructTypeConstant.W_SEARCH_INFO.getKey();
        }
        String ip = "/" + tWeGatewayConfig.getGatewayIp() + ":" + tWeGatewayConfig.getGatewayPort();
        Object[] openElectricities = sendInstructsService.sendInstructs(instruct, ip, request, equipmentNumber, operationType);
        return true;
    }

    @Override
    public boolean get(Long type) {
        String instruct = null;
        //操作类型
        String operationType = null;
        if (String.valueOf(type).equals(InstructTypeConstant.E_BALANCE_SETUPA.getKey())) {
            LambdaQueryWrapper<TWeEquipment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TWeEquipment::getEquipmentType, "电表");
            List<TWeEquipment> tWeEquipments = this.baseMapper.selectList(queryWrapper);
            for (TWeEquipment tWeEquipment : tWeEquipments) {
                //抄表记录
                TWeGatewayConfig tWeGatewayConfig = tWeGatewayConfigDao.selectById(tWeEquipment.getEquipmentGateway());
                String s1 = ElectricityMeterUtil.deviceAddressConvert(tWeEquipment.getEquipmentNumber());
                instruct = ElectricityMeterUtil.getCompleteInstruct(s1, InstructConstant.ELECTRICITY_BALANCE);
                operationType = InstructTypeConstant.E_BALANCE_SETUPA.getKey();
                String ip = "/" + tWeGatewayConfig.getGatewayIp() + ":" + tWeGatewayConfig.getGatewayPort();
                Object[] openElectricities = sendInstructsService.sendInstructs(instruct, ip, null, tWeEquipment.getEquipmentNumber(), operationType);
            }
        }
        return true;
    }


    //定时进行抄表
    @Transactional(rollbackFor = Exception.class)
//    @Scheduled(cron = "0 0/2 * * * ?")
    public void meterReading() {
        String instruct = null;
        String opType = null;
        //拿到所有的设备
        List<TWeEquipment> tWeEquipments = this.baseMapper.selectList(null);
        //分别进行抄表
        for (TWeEquipment tWeEquipment : tWeEquipments) {
            //先判断是否在线
            //查找网关是否在线
            Integer gatewayStatus = tWeGatewayConfigDao.selectById(tWeEquipment.getEquipmentGateway()).getGatewayStatus();
            if (gatewayStatus == 1) {
                String s = ElectricityMeterUtil.deviceAddressConvert(tWeEquipment.getEquipmentNumber());
                //在线就查询
                if ("电表".equals(tWeEquipment.getEquipmentType())) {
                    //发送指令
                    instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.ELECTRICITY_BALANCE);
                    opType = InstructTypeConstant.E_BALANCE_SETUPA.getKey();
                }
                if ("水表".equals(tWeEquipment.getEquipmentType())) {
                    //发送指令
                    instruct = ElectricityMeterUtil.getCompleteInstruct(s, InstructConstant.WATER_METER_READ_DATA);
                    opType = InstructTypeConstant.W_SEARCH_INFO.getKey();
                }
                TWeGatewayConfig tWeGatewayConfig = tWeGatewayConfigDao.selectById(tWeEquipment.getEquipmentGateway());
                String ip = "/" + tWeGatewayConfig.getGatewayIp() + ":" + tWeGatewayConfig.getGatewayPort();
                Object[] openElectricities = sendInstructsService.sendInstructs(instruct, ip, null, tWeEquipment.getEquipmentNumber(), opType);
                System.out.println(1);
            }
        }
    }
}

